<!-- views/AcceptInvitation.vue -->
<template>
  <div class="accept-invitation-container">
    <div class="invitation-card">
      <div class="invitation-header">
        <img src="@/assets/logo.svg" alt="灵犀" class="logo">
        <h1 class="system-name">小采灵犀智能对账系统</h1>
      </div>
      
      <div v-if="loading" class="loading-content">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="invitationValid" class="invitation-content">
        <el-result 
          icon="success" 
          title="邀请确认" 
          :sub-title="`您被邀请加入 ${invitationData?.organization?.name}`"
        >
          <template #extra>
            <div class="invitation-details">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="邀请组织">
                  {{ invitationData?.organization?.name }}
                </el-descriptions-item>
                <el-descriptions-item label="邀请角色">
                  {{ invitationData?.role }}
                </el-descriptions-item>
                <el-descriptions-item label="邀请人">
                  {{ invitationData?.inviter?.name }}
                </el-descriptions-item>
                <el-descriptions-item label="邀请时间">
                  {{ formatDate(invitationData?.createdAt) }}
                </el-descriptions-item>
              </el-descriptions>
              
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="large" 
                  @click="acceptInvitation"
                  :loading="accepting"
                >
                  接受邀请
                </el-button>
                <el-button 
                  size="large" 
                  @click="declineInvitation"
                >
                  拒绝邀请
                </el-button>
              </div>
            </div>
          </template>
        </el-result>
      </div>
      
      <div v-else class="error-content">
        <el-result 
          icon="error" 
          title="邀请无效" 
          :sub-title="errorMessage"
        >
          <template #extra>
            <el-button type="primary" @click="goToLogin">前往登录</el-button>
          </template>
        </el-result>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// @ts-ignore
import { ref, onMounted } from '@vue/runtime-core'
// @ts-ignore
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as invitationApi from '@/api/invitation'

// 路由和路由参数
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const accepting = ref(false)
const invitationValid = ref(false)
const invitationData = ref<any>(null)
const errorMessage = ref('邀请链接无效或已过期')

// 方法
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const validateInvitation = async () => {
  const token = route.query.token as string
  if (!token) {
    errorMessage.value = '缺少邀请令牌'
    loading.value = false
    return
  }
  
  try {
    const response = await invitationApi.invitationAPI.validateInvitation(token)
    if (response.success) {
      invitationValid.value = true
      invitationData.value = response.data
    } else {
      errorMessage.value = response.message || '邀请链接无效或已过期'
    }
  } catch (error) {
    console.error('验证邀请失败:', error)
    errorMessage.value = '验证邀请失败: ' + (error as Error).message
  } finally {
    loading.value = false
  }
}

const acceptInvitation = async () => {
  const token = route.query.token as string
  if (!token) {
    ElMessage.error('缺少邀请令牌')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要接受加入 ${invitationData.value?.organization?.name} 的邀请吗？`,
      '接受邀请',
      {
        type: 'warning',
        confirmButtonText: '确定接受',
        cancelButtonText: '取消'
      }
    )
    
    accepting.value = true
    const response = await invitationApi.invitationAPI.acceptInvitation(token)
    if (response.success) {
      ElMessage.success('邀请接受成功，即将跳转到系统首页')
      setTimeout(() => {
        router.push('/')
      }, 2000)
    } else {
      ElMessage.error(response.message || '接受邀请失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('接受邀请失败:', error)
      ElMessage.error('接受邀请失败: ' + (error as Error).message)
    }
  } finally {
    accepting.value = false
  }
}

const declineInvitation = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要拒绝此邀请吗？',
      '拒绝邀请',
      {
        type: 'warning',
        confirmButtonText: '确定拒绝',
        cancelButtonText: '取消'
      }
    )
    
    ElMessage.info('您已拒绝此邀请')
    router.push('/login')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('拒绝邀请失败:', error)
      ElMessage.error('拒绝邀请失败: ' + (error as Error).message)
    }
  }
}

const goToLogin = () => {
  router.push('/login')
}

// 生命周期
onMounted(() => {
  validateInvitation()
})
</script>

<style scoped>
.accept-invitation-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.invitation-card {
  width: 100%;
  max-width: 500px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
}

.invitation-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 60px;
  height: 60px;
  margin-bottom: 15px;
}

.system-name {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.invitation-details {
  width: 100%;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  gap: 15px;
  justify-content: center;
}

.action-buttons .el-button {
  min-width: 120px;
}

.loading-content {
  padding: 30px 0;
}

.error-content,
.invitation-content {
  padding: 20px 0;
}
</style>